<template>
	<view class="theme_bg_vice_color">
		<cu-custom :isBack="true" :bgColor="'bg-white'" :backColor="'text-black'">
			<block slot="backText">
				<view class="text-black ">{{ ScriptInfo.name }}</view>
			</block>
		</cu-custom>

		<view class="padding-bottom-xl" style="background-color: #fff;height: auto;">
			<view class="cu-card article text-black">
				<view class=" shadow padding-sm">
					<view class="flex justify-start">
						<image :src="$isHttp(ScriptInfo.picture)" style="width: 220rpx;height: 300rpx;" class="radius12" mode="aspectFill"></image>
						<view class="desc margin-left-sm">
							<view class="flex justify-start margin-top-xs">
								<view class="text-bold ">{{ ScriptInfo.name }}</view>
							</view>
							<view class="margin-top-sm text-sm">
								人数：{{ ScriptInfo.number }}人
								<text>{{ ScriptInfo.sex_type }}</text>
							</view>
							<view class="margin-top-xs text-sm flex align-end">
								价格：
								<view class="flex align-end text-yellow">
									<view class="text-sm ">会员价¥</view>
									<view class="text-lg text-bold">{{ ScriptInfo.member_price }}</view>
									<view class="text-sm ">/位</view>
									<view class="text-lg text-gray" style="text-decoration:line-through">{{ ScriptInfo.price }}</view>
								</view>
							</view>
							<view class="margin-top-xs text-sm">难度：{{ ScriptInfo.difficulty }}</view>
							<view class="margin-top-xs text-sm">时长：{{ ScriptInfo.hour }}小时</view>
							<view class="margin-top-xs text-sm">发行：{{ ScriptInfo.issue_name }}</view>
						</view>
					</view>
				</view>
			</view>

			<view class="margin-sm dm"><view class="margin-bottom-sm text-bold">请根据剧本选择时间</view></view>
			<button @click="showModal" data-target="bottomModal" type="" class="round text-white margin-sm text-df" style="background-color: #4d4d4d;">
				{{ timeAppointment == '' ? '选择时间' : timeAppointment }} {{ ScriptInfo.number }}人
			</button>

			<view class="margin-sm dm flex justify-between" v-show="!isBussiness">
				<view class="flex justify-start align-center" @click="map">
					<view class="cuIcon-location test-lg text-gray"></view>
					<view>
						<view class="text-bold">{{ vuex_bussiness.store_name }}</view>
						<view class="text-sm text-gray">{{ vuex_bussiness.address }}</view>
					</view>
				</view>
				<view class="flex justify-end">
					<view @click="callPhone(vuex_bussiness.telephone)">
						<image src="../../static/icon/dianhua.png" style="width: 54rpx;height: 40rpx;" mode=""></image>
						<view>电话</view>
					</view>
				</view>
			</view>
			<view class="margin-sm dm" v-show="isBussiness"><view class="text-bold">选择商家查看详细地址</view></view>

			<view class="margin-sm dm" v-if="bussinesList.length > 0">
				<view class="flex justify-between">
					<view class="margin-bottom-sm text-bold">选择商家</view>
					<view class="" @click="BussinessShow = true">
						更多
						<text class="cuIcon-right"></text>
					</view>
				</view>
				<scroll-view class="scroll-view_H" scroll-x="true" scroll-left="0">
					<view
						@click="getBussinesInfoById(item.id, item.StoreName, item.city + item.region, item.address)"
						data-target="Image"
						v-for="(item, index) in bussinesList.slice(0, 3)"
						:key="index"
						class="cu-card dm-item scroll-view-item_H radius"
					>
						<image class="radius" :src="$isHttp(item.picture)" mode="aspectFill"></image>
						<view class="">
							<view class="text-sm text-black padding_le_10 text-cut margin-top-xs">{{ item.StoreName }}</view>
							<view class="text-sm text-grey padding_le_10 text-cut margin-top-xs">{{ item.address }}</view>
						</view>
						<image v-show="vuex_bussinessId == item.id" class="select" src="../../static/icon/select.png" mode=""></image>
					</view>
				</scroll-view>
			</view>
			<van-popup :show="BussinessShow" position="bottom" custom-style="height: 60%;" @close="BussinessShow = false" @click-overlay="BussinessShow = false">
				<scroll-view style="height: 100%;" scroll-y="true" @scrolltolower="lower">
					<view class="text-center text-bold padding-top-sm fixed">选择商家</view>
					<van-radio-group :value="vuex_bussinessId" @change="this.vuex_bussinessId = $event.detail">
						<van-cell-group>
							<van-search :value="value" placeholder="请输入搜索关键词" @search="searchBusiness" />
							<van-cell
								clickable
								data-name="1"
								@click="getBussinesInfoById(item.id, item.StoreName, item.city + item.region, item.address)"
								v-for="(item, index) in bussinesList"
								:key="index"
							>
								<view slot="title">
									<view class="flex justify-start">
										<image :src="$isHttp(item.picture)" mode="aspectFill" class="radius12" style="height: 100rpx;width: 100rpx;"></image>
										<view class="padding-tb-xs flex-direction justify-between margin-left-xs">
											<view class="text-bold">{{ item.StoreName }}</view>
											<view class="flex justify-between text-sm align-center">
												<view class="text-cut" style="width: 320rpx;">{{ item.address }}</view>
												<view>{{ item.distance }}km</view>
											</view>
										</view>
									</view>
								</view>
								<van-radio slot="right-icon" :name="item.id" checked-color="#dcc512" />
							</van-cell>
							<view class="text-sm text-center">{{ tip }}</view>
						</van-cell-group>
					</van-radio-group>
				</scroll-view>
			</van-popup>
			<view class="margin-sm dm " v-show="roomLen">
				<view class="margin-bottom-sm text-bold">选择房间(可不选)</view>
				<scroll-view class="scroll-view_H" scroll-x="true" scroll-left="0">
					<view @click="getRoom(item.id)" data-target="Image" v-for="(item, index) in roomList" :key="index" class="cu-card dm-item scroll-view-item_H radius">
						<image class="radius" :src="$isHttp(item.picture)" mode="aspectFill"></image>
						<view class="">
							<!-- <view class="tj1 cu-tag radius sm text-white"><text
									class="lg text-white cuIcon-hot"></text>1234</view> -->
							<view class="text-sm text-black padding_le_10 text-cut margin-top-xs">{{ item.name }}</view>
							<!-- <view class="text-sm text-grey padding_le_10 text-cut margin-top-xs">{{item.address}}</view> -->
						</view>
						<image v-show="selectRoom == item.id" class="select" src="../../static/icon/select.png" mode=""></image>
					</view>
				</scroll-view>
			</view>

			<view class="margin-sm dm">
				<view class="margin-bottom-sm text-bold">拼车备注</view>
				<view class="solids padding radius12"><input class="text-xl" type="text" v-model="remarks" placeholder="备注(20字,可不填)" :maxlength="20" /></view>
			</view>

			<view class="margin-sm radius padding-sm text-white" style="background-image: linear-gradient(to right, #515151 , #202020);">
				<view>温馨提示：</view>
				<view class="text-sm margin-top-sm">“预约之后可以分享给小伙伴们，让小伙伴们加入哦”</view>
			</view>
			<view class="padding-tb-sm"></view>
			<button
				v-if="vuex_user.phone == '' || vuex_user.phone == null"
				data-target="bottomModal"
				class="text-center text-white text-lg text-bold"
				style="line-height: 100rpx;background-color: #d0a466;position: fixed;bottom: 0;width: 100%;height: 100rpx;"
				open-type="getPhoneNumber"
				@getphonenumber="makeAppointment"
			>
				<!-- open-type="getPhoneNumber"
				@getphonenumber="getPhoneNumber" -->
				立即预约
			</button>
			<button
				v-else
				data-target="bottomModal"
				class="text-center text-white text-lg text-bold"
				style="line-height: 100rpx;background-color: #d0a466;position: fixed;bottom: 0;width: 100%;height: 100rpx;"
				@click="makeAppointment"
			>
				<!-- open-type="getPhoneNumber"
				@getphonenumber="getPhoneNumber" -->
				立即预约
			</button>
		</view>

		<!-- //底部窗口 -->
		<view class="cu-modal bottom-modal" :class="modalName == 'bottomModal' ? 'show' : ''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-green"></view>
					<view class="action text-blue" @click="hideModal">取消</view>
				</view>
				<view class="padding-xl-sm padding-bottom-xl"><pretty-timespicker @change="getTime" disableText="已约满"></pretty-timespicker></view>
			</view>
		</view>

		<van-popup :show="payBeforPop" round @close="payBeforPop = false" close-on-click-overlay>
			<view style="width: 600rpx;height: auto;padding: 30rpx;">
				<van-cell-group inset>
					<van-cell title="买单金额" icon="shopping-cart">
						<view slot="">
							<view class="text-lg text-red">￥{{ payInfo.price }}</view>
						</view>
					</van-cell>
					<van-cell title="会员折扣" icon="vip-card" v-show="selectGemIndex === -1" >
							<view :class="{'text-bold':payInfo.member?true:false, 'text-yellow':payInfo.member?true:false}">
								{{!payInfo.member ? '未开通会员' : payInfo.member + '折'}}
							</view>
					</van-cell>
					<van-cell
						title="优惠券"
						icon="coupon"
						:label="selectCouponIndex === -1 ? '' : payInfo.coupon[selectCouponIndex].type === 0 ? '满' + payInfo.coupon[selectCouponIndex].number + '减' + payInfo.coupon[selectCouponIndex].number_reduce:'满' + payInfo.coupon[selectCouponIndex].number + '打' + payInfo.coupon[selectCouponIndex].number_reduce+'折'"
						@click="showModal"
						data-target="coupon"
						is-link
						v-show="selectGemIndex === -1"
					>
						<view :class="{'text-green':payInfo.coupon.length >0?true:false}">
							{{payInfo.coupon.length === 0 ? '无可用优惠券' :selectCouponIndex === -1 ? '可使用优惠券' : payInfo.coupon[selectCouponIndex].name}}
						</view>
					</van-cell>
					<van-cell
						title="钻石卡"
						icon="gem"
						@click="showModal"
						data-target="gem"
						is-link
					>
					<view :class="{'text-green':payInfo.userCar.length >0?true:false}">{{payInfo.userCar.length === 0 ? '无可用钻石卡' : selectGemIndex === -1 ? '可使用钻石卡' : '使用钻石卡'}}</view>
					</van-cell>
					<van-cell center @click="payType = !payType" v-show="selectGemIndex === -1">
						<template #title>
							<view>
								我的余额:
								<text class="text-green">{{ payInfo.balance }}</text>
								元
							</view>
						</template>
						<template #right-icon>
							{{ payType ? '微信支付' : '余额支付' }}
							<van-switch :value="payType" size="24" inactive-color="#61ba37" active-color="#b6981d" />
						</template>
					</van-cell>
				</van-cell-group>
				<view class="text-center margin-tb-xs" v-show="selectGemIndex === -1">
					<text class="text-yellow">￥</text>
					<text class="text-yellow text-sl">{{ PaidIn }}</text>
					<text class="text-yellow">元</text>
				</view>
				<view class="text-center text-orange margin-tb-xs" v-show="selectGemIndex === -1">(以实付金额为准)</view>
				<van-button type="primary" color="#3b301a" @click="Payment" block>{{ selectGemIndex === -1 ? '支付' : '使用钻石卡预约' }}</van-button>
			</view>
		</van-popup>
		<van-popup :show="modalName == 'coupon'" round position="bottom" @close="modalName = ''" close-on-click-overlay>
			<view class="padding" style="max-height: 600rpx;">
				<van-radio-group v-model="selectCoupon">
					<van-cell-group>
						<van-cell
							@click="
								modalName = '';
								selectCouponIndex === index ? (selectCouponIndex = -1) : (selectCouponIndex = index);
								selectCouponIndex === index ? (selectCoupon = item.id) : (selectCoupon = '');
							"
							:title="item.name"
							:label="item.type === 0 ? '满' + item.number + '减' + item.number_reduce : '满' + item.number + '打' + item.number_reduce + '折'"
							v-for="(item, index) in payInfo.coupon"
							:key="index"
							clickable
						>
							<template #right-icon>
								<van-radio :name="item.id" />
							</template>
						</van-cell>
					</van-cell-group>
				</van-radio-group>
			</view>
		</van-popup>
		<van-popup :show="modalName == 'gem'" round position="bottom" @close="modalName = ''" close-on-click-overlay>
			<view class="padding" style="max-height: 600rpx;">
				<van-radio-group v-model="selectGem">
					<van-cell-group>
						<van-cell
							@click="
								modalName = '';
								selectGemIndex === index ? (selectGemIndex = -1) : (selectGemIndex = index);
								selectGemIndex === index ? (selectGem = item.id) : (selectGem = '');
							"
							:title="'钻石卡'"
							:label="'有效期至' + item.expiration_time.split(' ')[0]"
							:value="'剩余可用次数:' + (item.count_surplus <0 ? '无限次' : item.count_surplus)"
							v-for="(item, index) in payInfo.userCar"
							:key="index"
							clickable
						>
							<template #right-icon>
								<van-radio :name="item.id" />
							</template>
						</van-cell>
					</van-cell-group>
				</van-radio-group>
			</view>
		</van-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			value: '', //搜索商家关键词
			modalName: '', //模态框名称
			ScriptInfoData:'',
			
			bussinesList: [], //商家列表
			BussinessShow: false,
			roomList: [], //房间列表
			// selectBussines: -1, //选择的商家
			selectRoom: -1, //选择的房间
			// selectBussinesName: '', //选择的商家的名称
			// selectBussinesCity: '', //选择的商家所在城市
			// selectBussinesAddress: '', //选择的商家的详细地址
			remarks: '', //备注

			payInfo: '', //支付前信息
			payBeforPop: false,

			selectGemIndex: -1, //选择的钻石卡下标
			selectGem: '', //选择的钻石卡id

			selectCouponIndex: -1, //选择的优惠券下标
			selectCoupon: '', //选择的优惠券id
			// PaidIn:0,  //实付金额
			payType: false, //支付方式，false余额，true微信

			isPay: false, //是否支付

			timeAppointment: '', //选择的预约时间
			week: '',

			page: 1,
			tip: '加载中...'
		};
	},
	watch: {
		payBeforPop: function(newVal, oldVal) {
			if (newVal) {
				this.$u.api
					.payBefore({
						userId: this.vuex_user.id,
						orderId: '',
						playId: this.ScriptInfo.id,
						storeId: this.vuex_bussinessId
					})
					.then(res => {
						this.payInfo = res.data;
					});
			}
		},
		vuex_bussiness: function() {
			this.isBussiness = JSON.stringify(this.vuex_bussiness) == '{}' ? true : false;
			console.log(this.isBussiness);
		}
	},
	computed: {
		isBussiness: function() {
			return JSON.stringify(this.vuex_bussiness) == '{}';
		},
		PaidIn: function() {
			let num = this.payInfo.price;
			if(this.payInfo.member){
				num=this.payInfo.price*this.payInfo.member/10
			}
			if (this.selectCouponIndex !== -1) {
				if (this.payInfo.coupon[this.selectCouponIndex].type === 0) {
					num=this.$subNum(num,this.payInfo.coupon[this.selectCouponIndex].number_reduce)
				} else {
					num = (num * this.payInfo.coupon[this.selectCouponIndex].number_reduce) / 10;
				}
			}
			num = Math.floor(num * 100) / 100; //保留两位小数，不四舍五入
			num=this.$amountCvs(num,2)
			if (num < 0.01) return '0.00';
			return num;
		},
		roomLen: function() {
			return this.roomList.length === 0 ? false : true;
		}
	},
	onLoad(option) {
		if (this.vuex_bussinessId !== '') {
			this.$u.api
				.getBussinesInfoById({
					store_id: this.vuex_bussinessId
				})
				.then(res => {
					this.roomList = res.data.room;
				});
				if(option.id){
					this.$u.api.getScriptInfo({
						userId: this.vuex_user.id?this.vuex_user.id:'',
						playId: option.id,
						storeId:this.vuex_bussinessId
					}).then(res => {
						this.ScriptInfoData = res.data.xiang
						
						this.ScriptInfoData.picture=this.$isHttp(this.ScriptInfoData.picture)
						this.ScriptInfoData.smallClasses=this.ScriptInfoData.smallClasses.slice(0,5)
						
						this.$u.vuex('ScriptInfo', this.ScriptInfoData);
					})
				}
			if (this.vuex_userCarId != -1) {
				this.selectGem = this.vuex_userCarId;
				this.selectGemIndex = '';
			}
		} else {
			// this.lower();
		}
	},
	onUnload() {
		if (this.vuex_bussinessEnter === 0) {
			this.$u.vuex('vuex_bussinessId', '');
			this.$u.vuex('vuex_bussiness', {});
		}
	},
	methods: {
		//预约
		makeAppointment(e) {
			if (this.vuex_bussinessId == '') {
				this.$textToast('请选择商家');
				return;
			}
			if (this.timeAppointment == '') {
				this.$textToast('请选择预约时间');
				return;
			}
			if(!this.vuex_user.phone){
				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
					//用户决绝授权
					//拒绝授权后弹出一些提示
					this.$textToast('请绑定手机号，接收预约信息');
				} else {
					//允许授权
					console.log(e.detail.encryptedData);
					// e.detail.encryptedData      //加密的用户信息
					// e.detail.iv     //加密算法的初始向量  时要用到
					this.$u.api
						.getUserPhone({
							encryptedData: e.detail.encryptedData,
							iv: e.detail.iv,
							userId: this.vuex_user.id
						})
						.then(res => {
							if (res.code === 200) {
								let vuex_user=this.vuex_user
								vuex_user.phone=res.data.phoneNumber
								this.$u.vuex('vuex_user', vuex_user);
								this.payBeforPop = true;
							}
						});
				}
			}else{
				this.payBeforPop = true;
			}
			
		},
		Payment() {
			if(this.PaidIn==0.00){
				this.payType = false;
			}
			if (!payType && this.payInfo.balance < this.PaidIn) {
				this.$textToast('余额不足，已选择微信支付');
				this.payType = true;
			}
			let payType = this.payType ? 1 : 0;
			if (this.selectGem !== '') {
				payType = 2;
			}
			this.$u.api
				.AddOrder({
					playId: this.ScriptInfo.id,
					storeId: this.vuex_bussinessId,
					userId: this.vuex_user.id,
					date: this.timeAppointment.split(' ')[0],
					time: this.timeAppointment.split(' ')[1],
					people: this.ScriptInfo.number,
					roomId: this.selectRoom,
					week: this.week,
					remark: this.remarks,
					couponId: this.selectCoupon,
					payType: payType,
					userCarId: this.selectGem
				})
				.then(res => {
					if (res.code == 200) {
						this.payBeforPop = false;
						if (payType !== 1) {
							uni.showToast({
								title: '预约成功',
								icon: 'success',
								complete: () => {
									this.$goPage('./AppointmentProgress?id=' + res.data);
								}
							});
						} else {
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: res.data.returnPayInfoVO.timeStamp,
								nonceStr: res.data.returnPayInfoVO.nonceStr,
								package: 'prepay_id=' + res.data.returnPayInfoVO.prepayId,
								signType: res.data.returnPayInfoVO.signType,
								paySign: res.data.returnPayInfoVO.paySign,
								success: res1 => {
									uni.showToast({
										title: '预约成功',
										icon: 'success',
										complete: () => {
											this.$goPage('./AppointmentProgress?id=' + res.data.id);
										}
									});
								},
								fail: err => {
									console.log('fail:' + JSON.stringify(err));
								}
							});
						}
					}
				});
		},
		getRoom(id) {
			this.selectRoom = id;
		},
		getBussinesInfoById(id, businessName, city, address) {
			this.BussinessShow = false;
			if (this.vuex_bussinessId == id) return;
			this.$u.vuex('vuex_bussinessId', id);
			this.$u.vuex('vuex_bussiness', {
				store_name: businessName,
				address: city + address
			});
			this.$u.api
				.getBussinesInfoById({
					store_id: id
				})
				.then(res => {
					this.roomList = res.data.room;
				});
		},
		searchBusiness(e) {
			console.log(e.detail);
		},
		async map() {
			//地理编码，获取经纬度
			let re = await uni.request({
				//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
				url: 'https://restapi.amap.com/v3/geocode/geo?parameters?output=JSON&address=' + this.vuex_bussiness.address + '&key=7b7fbe6751d2491c692a1728a6c7afa4'
			});
			let location = re[1].data.geocodes[0].location.split(',');
			await uni.openLocation({
				latitude: parseFloat(location[1]),
				longitude: parseFloat(location[0]),
				name: this.vuex_bussiness.store_name,
				address: this.vuex_bussiness.address,
				success: function() {
					console.log('success');
				}
			});
		},
		getTime(e) {
			console.log(e);
			this.timeAppointment = e;
			this.week = this.$getWeekDate(e.split(' ')[0]);
			this.hideModal();
		},
		lower() {
			if (this.tip === '加载中...') {
				this.$u.api
					.getBussinesListByPlayAndCity({
						city: this.vuex_city,
						play_id: this.ScriptInfo.id,
						longitude: this.vuex_longitude,
						latitude: this.vuex_latitude,
						page: this.page,
						number: 10
					})
					.then(res => {
						this.bussinesList = this.bussinesList.concat(res.data);
						this.page++;
						if (res.data.length < 10) {
							this.tip = '没有更多了';
						}
						if (res.data.length === 0 && this.bussinesList.length === 0) {
							uni.showToast({
								title: '暂无商家添加此剧本',
								icon: 'none',
								mask: true,
								duration: 3000
							});
						}
					});
			}
		},
		callPhone(telephone) {
			uni.makePhoneCall({
				phoneNumber: telephone //仅为示例
			});
		},
		showModal(e) {
			if (e.currentTarget.dataset.target === 'coupon' && this.payInfo.coupon.length === 0) {
				this.$textToast('无可用优惠券');
				return;
			}
			if (e.currentTarget.dataset.target === 'gem' && this.payInfo.userCar.length === 0) {
				this.$textToast('无可用钻石卡');
				return;
			}
			this.modalName = e.currentTarget.dataset.target;
		},
		hideModal(e) {
			this.modalName = '';
		}
	}
};
</script>

<style lang="scss" scoped>
// 主持人
.supporter {
	background-color: #fff;
}

.padding_top_5 {
	padding-top: 5rpx;
}

.padding_le_10 {
	padding-left: 10rpx;
}

.scroll-view_H {
	white-space: nowrap;
	width: 100%;
}

.scroll-view-item_H {
	display: inline-block;
}

.dm {
	width: auto;

	.dm-item {
		width: 210rpx;
		height: 239rpx;
		// background-color: #fff;
		margin-left: 15rpx;
		overflow: hidden;

		&:nth-child(1) {
			margin-left: 0;
		}

		image {
			width: 100%;
			height: 56%;
		}

		position: relative;

		.select {
			width: 50rpx;
			height: 50rpx;
			position: absolute;
			top: 0;
			right: 0;
		}

		.text {
		}
	}
}
</style>
